//
//  CAShopCartViewController.m
//  LNH
//
//  Created by twentylx on 2018/1/15.
//  Copyright © 2018年 twentylx. All rights reserved.
//

#import "CAShopCartViewController.h"
#import "CAShopCartTableViewCell.h"
#import "CAShopCartBottomView.h"
#import "CAShopCartApi.h"
#import "CADelShopCartApi.h"
#import "CAUpdateShopCartApi.h"
#import "LNHConfirmOrderViewController.h"
#import "CALoginViewController.h"

@interface CAShopCartViewController () <UITableViewDataSource, UITableViewDelegate> {
    float _total;
    NSString *_cartIds;
}

@property (nonatomic, strong) UITableView *shopcartTableView;
@property (nonatomic, strong) CAShopCartBottomView *bottomView;

@property (nonatomic, strong) NSArray *shopcartArray;
@property (nonatomic, strong) NSMutableArray *selectArray;

@end

static NSString *CellIdentify = @"ShopCartCell";

@implementation CAShopCartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    if ([GVUD.token isEqualToString:@""] || GVUD.token == nil) {
//        CALoginViewController *loginVC = [CALoginViewController new];
//        loginVC.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:loginVC animated:YES];
//    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.selectArray = nil;
    _cartIds = nil;
    [self loadData];
    if (self.bottomView.totalLabel != nil) {
        self.bottomView.totalLabel.text = @"";
    }
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0
    self.navigationController.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>)self;
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
#endif
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0
- (UIRectEdge)edgesForExtendedLayout {
    return UIRectEdgeNone;
}
#endif

- (void)lm_initialDefaultsForController
{
}

- (void)lm_configNavigationForController
{
    self.navigationItem.title = @"购物车";
}

- (void)lm_createViewForController
{
    [self.view addSubview:self.shopcartTableView];
    [self.view addSubview:self.bottomView];
    
    [self.view setNeedsUpdateConstraints];
}

-(void)lm_bindViewModelForController
{
    
}

#pragma mark - Layout

- (void)updateViewConstraints
{
    [super updateViewConstraints];
    
    [_shopcartTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        make.top.equalTo(self.view);
        make.bottom.equalTo(self.bottomView);
        
    }];
    
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
        if (self.isHome) {
            make.height.mas_equalTo(44);
        } else {
            make.height.mas_equalTo(isIPhoneX ? 78 : 44);
        }
    }];
}

#pragma mark - Getter
- (UITableView *) shopcartTableView{
    if (!_shopcartTableView) {
        _shopcartTableView = [UITableView new];
        _shopcartTableView.dataSource = self;
        _shopcartTableView.delegate = self;
        _shopcartTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_shopcartTableView registerClass:[CAShopCartTableViewCell class] forCellReuseIdentifier:CellIdentify];
    }
    return _shopcartTableView;
}

- (CAShopCartBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [CAShopCartBottomView new];
        _bottomView.backgroundColor = [UIColor whiteColor];
        [[_bottomView.selectAllButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [self selectAllAction];
        }];
        
        [[_bottomView.submitButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            for (int i = 0; i < self.selectArray.count; i++) {
                BOOL isSelect = [self.selectArray[i] boolValue];
                if (isSelect) {
                    NSDictionary *dict = self.shopcartArray[i];
                    if ([_cartIds isEqualToString:@""] || _cartIds == nil) {
                        _cartIds = [NSString stringWithFormat:@"%@,", dict[@"id"]];
                    } else {
                        _cartIds = [NSString stringWithFormat:@"%@,%@,", _cartIds, dict[@"id"]];
                    }
                }
            }
            if (_cartIds == nil) {
                [SVProgressHUD lm_displayErrorWithStatus:@"请选择商品"];
                return;
            }
            
            NSString *router = [JLRoutes lm_generateURLWithPattern:LMNavPushRoute parameters:@[NSStringFromClass(LNHConfirmOrderViewController.class)] extraParameters:@{@"cartIds":_cartIds}];
            [[RACScheduler mainThreadScheduler] schedule:^{
                
                [[UIApplication sharedApplication] openURL:JLRGenRouteURL(LMDefaultRouteSchema, router) options:nil completionHandler:nil];
                
            }];
        }];
    }
    return _bottomView;
}

#pragma mark private method
- (void) loadData {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    CAShopCartApi *shopCartApi = [[CAShopCartApi alloc] init];
    [shopCartApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        CAShopCartApi *api = (CAShopCartApi *) request;
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (api.done) {
            self.shopcartArray = api.responseObject[@"result"];
            
            if (self.selectArray == nil) {
                self.selectArray = [NSMutableArray new];
                for (NSInteger i =0; i<self.shopcartArray.count; i++) {
                    [self.selectArray addObject:[NSNumber numberWithBool:NO]];
                }
            }
            
            [self calTotal];
            [self.shopcartTableView reloadData];
        } else {
            [SVProgressHUD lm_displayErrorWithStatus:api.errorMsg];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
    }];
}

- (void) selectActionWithIndex:(NSInteger) index Dict:(NSDictionary *) dict {
    BOOL isSelected = [self.selectArray[index] boolValue];
    if (isSelected) {
        [self.selectArray replaceObjectAtIndex:index withObject:[NSNumber numberWithBool:NO]];
        self.bottomView.selectAllButton.selected = NO;
    } else {
        [self.selectArray replaceObjectAtIndex:index withObject:[NSNumber numberWithBool:YES]];
    }
    [self.shopcartTableView reloadData];
    [self calTotal];
}

//删除
- (void) delActionWithCartId:(NSString *) cartId {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    CADelShopCartApi *delShopCartApi = [[CADelShopCartApi alloc] initCartIds:cartId];
    [delShopCartApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        CADelShopCartApi *api = (CADelShopCartApi *) request;
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (api.done) {
            self.selectArray = nil;
            [self loadData];
        } else {
            [SVProgressHUD lm_displayErrorWithStatus:api.errorMsg];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
    }];
}

//修改
- (void) updateActionWithCartId:(NSString *) cartId Number:(NSString *) number {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    CAUpdateShopCartApi *updateShopCartApi = [[CAUpdateShopCartApi alloc] initCartId:cartId Number:number];
    [updateShopCartApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        CAUpdateShopCartApi *api = (CAUpdateShopCartApi *) request;
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (api.done) {
//            self.selectArray = nil;
            [self loadData];
        } else {
            [SVProgressHUD lm_displayErrorWithStatus:api.errorMsg];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
    }];
}

- (void) selectAllAction {
    if (self.bottomView.selectAllButton.isSelected) {
        self.selectArray = [NSMutableArray new];
        for (NSInteger i =0; i<self.shopcartArray.count; i++) {
            [self.selectArray addObject:[NSNumber numberWithBool:NO]];
        }
        self.bottomView.selectAllButton.selected = NO;
    } else {
        self.selectArray = [NSMutableArray new];
        for (NSInteger i =0; i<self.shopcartArray.count; i++) {
            [self.selectArray addObject:[NSNumber numberWithBool:YES]];
        }
        self.bottomView.selectAllButton.selected = YES;
    }
    [self.shopcartTableView reloadData];
    [self calTotal];
}

- (void) calTotal {
    _total = 0;
    [self.selectArray enumerateObjectsUsingBlock:^(NSNumber *isSelect, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([isSelect boolValue]) {
            NSDictionary *dict = self.shopcartArray[idx];
            NSInteger number = [dict[@"number"] integerValue];
            float price = [dict[@"goods"][@"goods_price"] floatValue];
            _total = _total + number * price;
        }
    }];
    
    self.bottomView.totalPriceLabel.text = [NSString stringWithFormat:@"%.2f", _total];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.shopcartArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CAShopCartTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentify forIndexPath:indexPath];
//    cell = [[CAShopCartTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentify];
    cell.backgroundColor = [UIColor clearColor];
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.userInteractionEnabled = YES;
    
    NSDictionary *dict = _shopcartArray[indexPath.row];
    [cell configForCell:dict];
    
    NSNumber *isSelected = self.selectArray[indexPath.row];
    if ([isSelected boolValue]) {
        cell.selectButton.selected = YES;
    } else {
        cell.selectButton.selected = NO;
    }
    //选中
    [[[cell.selectButton rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self selectActionWithIndex:indexPath.row Dict:dict];
    }];
    //删除
    [[[cell.delButton rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self delActionWithCartId:dict[@"id"]];
    }];
    cell.stepper.incrementCallback = ^(PKYStepper * stepper,float count) {
        cell.stepper.countLabel.text = [NSString stringWithFormat:@"%@",@(count)];
        [self updateActionWithCartId:dict[@"id"] Number:[NSString stringWithFormat:@"%.f", count]];
    };
    cell.stepper.decrementCallback = ^(PKYStepper * stepper,float count) {
        cell.stepper.countLabel.text = [NSString stringWithFormat:@"%@",@(count)];
        [self updateActionWithCartId:dict[@"id"] Number:[NSString stringWithFormat:@"%.f", count]];
    };
    
    return cell;
}

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 150;
}

@end

